package com.ewentsai;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Result;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

@WebServlet(name = "login")
public class login extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        boolean isloginSuccess = false;
        Connection connection = DB.getConnection();
        Statement statement = DB.createStatement(connection);
        ResultSet rSet = DB.executeQuery(statement,"select * from users");
        String inputUsername = request.getParameter("UserName");
        String inputPassword = request.getParameter("Password");
        try {
            int loginResult = -1;
            while(rSet.next()){
                String username = rSet.getString("username");
                System.out.println(inputUsername);
                if(!inputUsername.equals(username)){
                    loginResult = 100;
                    continue;
                }
                String password = rSet.getString("password");
                if(inputPassword.equals(password)){
                    System.out.println("here");
                    loginResult = 111;
                    isloginSuccess = true;
                    break;
                }else{
                    System.out.println("there");
                    isloginSuccess = false;
                    loginResult = 110;
                    break;
                }
            }
            if(loginResult==111){
                response.sendRedirect("MainView.jsp?loginUserName="+inputUsername);
            }else{
                response.sendRedirect("loginResult.jsp?result="+loginResult);
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
    }
}
